@echo off
setlocal enabledelayedexpansion

:start
cls
echo ========================================
echo         文件MD5哈希值计算工具
echo ========================================
echo.

set "filepath="
set /p "filepath=请拖入文件或输入文件绝对路径: "

if "!filepath!"=="" (
    echo 错误：未输入文件路径
    pause
    goto start
)

:: 移除可能存在的引号
set "filepath=!filepath:"=!"

if not exist "!filepath!" (
    echo 错误：文件不存在 - "!filepath!"
    pause
    goto start
)

:: 获取文件名
for %%I in ("!filepath!") do (
    set "filename=%%~nxI"
    set "fullpath=%%~fI"
)

:: 获取当前日期时间
for /f "tokens=1-3 delims=/ " %%a in ('date /t') do (
    set currentdate=%%a-%%b-%%c
)
for /f "tokens=1-3 delims=: " %%a in ('time /t') do (
    set currenttime=%%a:%%b:%%c
)
set datetime=!currentdate! !currenttime!

:: 获取文件大小并转换单位
for %%I in ("!filepath!") do set "filesize_bytes=%%~zI"

:: 文件大小单位转换函数
call :ConvertFileSize !filesize_bytes! filesize_formatted
set "filesize_display=!filesize_formatted!"

:: 计算MD5哈希值
echo 正在计算MD5哈希值，请稍候...
set "md5hash="
for /f "skip=1 delims=" %%a in ('certutil -hashfile "!filepath!" MD5 2^>nul') do (
    if not defined md5hash set "md5hash=%%a"
)

if "!md5hash!"=="" (
    echo 错误：计算MD5哈希值失败
    pause
    goto start
)

:: 格式化输出
echo.
echo =============== 文件信息 ===============
echo 文件名称: !filename!
echo 文件路径: !fullpath!
echo 日期时间: !datetime!
echo 文件大小: !filesize_bytes! 字节 ^(!filesize_display!^)
echo MD5哈希值: !md5hash!
echo ========================================
echo.

:choice
set /p "continue=是否继续计算其他文件？(Y/N): "
if /i "!continue!"=="Y" goto start
if /i "!continue!"=="N" exit /b

echo 请输入Y或N
goto choice

:: 文件大小转换函数
:ConvertFileSize
setlocal
set "size=%1"
set "unit=B"

:: 转换为KiB (1024字节)
if !size! geq 1024 (
    set /a "size_kib=size/1024"
    set "size=!size_kib!"
    set "unit=KiB"
)

:: 转换为MiB (1024 KiB)
if !size! geq 1024 (
    set /a "size_mib=size/1024"
    set "size=!size_mib!"
    set "unit=MiB"
)

:: 转换为GiB (1024 MiB)
if !size! geq 1024 (
    set /a "size_gib=size/1024"
    set "size=!size_gib!"
    set "unit=GiB"
)

:: 转换为TiB (1024 GiB)
if !size! geq 1024 (
    set /a "size_tib=size/1024"
    set "size=!size_tib!"
    set "unit=TiB"
)

:: 格式化输出，保留2位小数
set "formatted_size=!size!"
if "!unit!" neq "B" (
    :: 计算小数部分
    if "!unit!"=="KiB" set /a "remainder=%1 %% 1024"
    if "!unit!"=="MiB" set /a "remainder=(%1 / 1024) %% 1024"
    if "!unit!"=="GiB" set /a "remainder=(%1 / 1048576) %% 1024"
    if "!unit!"=="TiB" set /a "remainder=(%1 / 1073741824) %% 1024"
    
    if !remainder! gtr 0 (
        set /a "decimal=remainder * 100 / 1024"
        if !decimal! lss 10 set "decimal=0!decimal!"
        set "formatted_size=!size!.!decimal!"
    )
)

endlocal & set "%2=%formatted_size% %unit%"
goto :eof